/*
 * Java Card File Parser 
 * Based on openjcvm project 
 */
package org.naive.metawatch.converter.parser;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.Field;

/**
 *
 * @author Andrew Butenko
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ParsedArray {

    FieldSize indexSize();

    Class<? extends Parseable> itemClass();

    public class FieldParser {

        public static Object parse(ParsedArray p, ParseContext x, Field f) throws Exception {
            int size = x.readU(p.indexSize());
            Class<?> componentType = f.getType().getComponentType();
            final Object array = Array.newInstance(componentType, size);
            for (int i = 0; i < size; i++) {
                final Parseable item = p.itemClass().newInstance();
                item.parse(x);
                Array.set(array, i, item);
            }
            return array;
        }
    }
}